package com.gitee.wsl.security.encrypt.sample

import com.gitee.wsl.ext.base.circleIndex
import com.gitee.wsl.ext.base.xor
import com.gitee.wsl.ext.string.toByteArray
import com.gitee.wsl.security.encrypt.Encrypt
import com.gitee.wsl.security.encrypt.StringToStringEncrypt
import kotlin.collections.mapIndexed


/**
 * https://www.jisuan.mobi/vHbummzm1Bb6UXQQ.html
 *
 * @author Leon
 * @since 2023-02-03 10:55
 * @email deadogone@gmail.com
 */
private const val DICT_TYPE7 = "dsfd;kfoA,.iyewrkldJKDHSUBsgvca69834ncxv9873254k;fg87"

object Type7 :StringToStringEncrypt{
    val seed:Int = 0

    override fun encrypt(src: String): String =
        src.type7(seed)

    override fun decrypt(src: String): String =
        src.type7Decode()

}

val Encrypt.Companion.type7 get() = Type7


internal fun String.type7(seed: Int = 0) =
    seed.toString().padStart(2, '0') +
            toByteArray()
                .mapIndexed { i, c ->
                    val t = (seed + i).circleIndex(53)
                    c xor DICT_TYPE7[t].code
                }
                .toByteArray()
                .toHexString()

internal fun String.type7Decode(): String {
    val seed = substring(0, 2).toInt()
    println(seed)
    return drop(2)
        .chunked(2)
        .mapIndexed { i, s ->
            val t = (seed + i).circleIndex(53)
            s.hex2ByteArray()[0] xor DICT_TYPE7[t].code
        }
        .toByteArray()
        .decodeToString()
}
